/*
 * Copyright (c)  2020,  DataPipeline
 * All rights reserved.
 *
 * Id:StringTypeHandler.java   2020-07-18 21:44 wanglijun
 */
package cn.datacare.orm.mapping.type.handler;

import cn.datacare.orm.dialect.DialectType;
import cn.datacare.orm.mapping.type.JavaSqlTypeHandler;
import cn.datacare.orm.mapping.type.TypeParameter;
import cn.datacare.orm.util.ClobUtils;

import java.io.Reader;
import java.sql.*;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2020
 * </p>
 * <p>
 * Company/Department: DataPipeline
 * </p>
 *
 * @author wanglijun
 * @version 1.0
 * @since 2020-07-18 21:44
 */
public class StringTypeHandler implements JavaSqlTypeHandler {

    /***
     *   基础类，用来sql到java，java到sql的映射
     * @param typeParameter
     * @return Object
     * @throws SQLException
     */
    @Override
    public Object getValue(TypeParameter typeParameter) throws SQLException {
        ResultSet resultSet = typeParameter.getResultSet();
        int index = typeParameter.getIndex();
        if (DialectType.ORACLE.name().equals(typeParameter.getDialectName())) {
            return this.getClob(typeParameter.getResultSetMetaData(), resultSet, index);
        }
        return resultSet.getString(index);
    }

    /***
     * 获取 Oracle Clob字段
     * @param resultSetMetaData
     * @param resultSet
     * @param index
     * @return Object
     */
    private Object getClob(ResultSetMetaData resultSetMetaData, ResultSet resultSet, int index) throws SQLException {
        int type = resultSetMetaData.getColumnType(index);
        switch (type) {
            case java.sql.Types.CLOB: {
                Clob clob = resultSet.getClob(index);
                if (clob == null) {
                    return null;
                }
                Reader reader = clob.getCharacterStream();
                return ClobUtils.getString(reader);
            }
            case Types.NCLOB: {
                NClob nclob = resultSet.getNClob(index);
                if (nclob == null) {
                    return null;
                }
                Reader reader = nclob.getCharacterStream();
                return ClobUtils.getString(reader);
            }

            default:
                return resultSet.getString(index);

        }
    }
}
